package cn.stylefeng.guns.modular.cb.service.impl;

import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.auth.model.LoginUser;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.cb.entity.CbMessages;
import cn.stylefeng.guns.modular.cb.mapper.CbMessagesMapper;
import cn.stylefeng.guns.modular.cb.model.params.*;
import cn.stylefeng.guns.modular.cb.model.result.*;
import cn.stylefeng.guns.modular.cb.service.*;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ss
 * @since 2021-01-19
 */
@Service
public class CbMessagesServiceImpl extends ServiceImpl<CbMessagesMapper, CbMessages> implements CbMessagesService {

    private static Logger logger = LoggerFactory.getLogger(CbMessagesServiceImpl.class);

    @Autowired
    private CbCustomerStudentsService studentsService;
    @Autowired
    private CbCustomerStaffService staffService;
    @Autowired
    private CbCustomerCompanyService companyService;

    @Autowired
    private CbCustomerService cbCustomerService;

    @Autowired
    private CbMessageTemplateService messageTemplateService;

    /**
     * 获取消息模板
     * @param userId
     * @param type
     * @return
     */
    private String messageContent(Long userId, Long type, String message) {
        CbCustomerParam param = new CbCustomerParam();
        //获取消息模板
        CbMessageTemplateParam mtParam = new CbMessageTemplateParam();
        JSONObject msgObj = new JSONObject();
        try{
            param.setId(userId);
            CbCustomerResult result = cbCustomerService.getCustomer(param);//消息投递人

            if (type==3) {
                mtParam.setType("MT_JHLXFS");//交换联系方式
                msgObj.put("phone", result.getPhone());
                msgObj.put("vx", result.getVx());
                msgObj.put("msg", result.getName()+" 想和你交换联系方式");
            } else if (type==6){
                mtParam.setType("MT_YQTD");//简历投递邀请
                msgObj.put("msg", "邀请投递职位可以内推");
            }else if (type==1) {//关注
                msgObj = JSONObject.parseObject(message);
            } else {
                msgObj.put("msg", message);
            }
            if (StringUtils.isEmpty(mtParam.getType())){//未配置模板
                return msgObj.toJSONString();
            }
            CbMessageTemplateResult mtResult = messageTemplateService.findBySpec(mtParam);
            if (mtResult!=null && mtResult.getId()!=null){
                msgObj.put("msg", mtResult.getDescription().replace("name", result.getName()));
            }
        }catch (Exception e) {
            logger.error("messageContent error", e);
        }
        return msgObj.toJSONString();
    }

    @Override
    public void add(CbMessagesParam param){
        //使用消息模板构建消息内容
        try{
            String msgt = messageContent(param.getSendUserid(), param.getType(), param.getMessage());//简历投递邀请
            param.setMessage(msgt);
            CbMessages entity = getEntity(param);
            this.save(entity);
            param.setId(entity.getId());

            if (entity.getType()==3){
                Long messageUserId = entity.getMessageUserid();
                CbCustomerParam cbCustomerParam = new CbCustomerParam();
                cbCustomerParam.setId(messageUserId);
                CbCustomerResult cbCustomerResult = cbCustomerService.getCustomer(cbCustomerParam);
                Integer contactSet = cbCustomerResult.getContactSet();
                if (!StringUtils.isEmpty(contactSet) && contactSet ==1){
                    //交换联系方式时，如果对方设置了自动获取，则执行同意操作
                    param.setEventid(1L);
                    this.update(param);//修改消息状态
                    //发送联系方式
                    String phone = cbCustomerResult.getPhone();
                    CbMessagesParam cbMessagesParam1 = new CbMessagesParam();
                    cbMessagesParam1.setMessageUserid(param.getSendUserid());
                    cbMessagesParam1.setSendUserid(param.getMessageUserid());
                    cbMessagesParam1.setType(3L);
                    cbMessagesParam1.setMessage(phone);
                    cbMessagesParam1.setStatus(0L);
                    cbMessagesParam1.setEventid(1L);
                    CbMessages entity1 = getEntity(cbMessagesParam1);
                    this.save(entity1);
                }
            }
        }catch (Exception e){
            logger.error("add error: ", e);
        }
    }

    @Override
    public void delete(CbMessagesParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(CbMessagesParam param){
        CbMessages oldEntity = getOldEntity(param);
        CbMessages newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
        param.setType(oldEntity.getType());
        param.setMessageUserid(oldEntity.getMessageUserid());
        param.setSendUserid(oldEntity.getSendUserid());
        param.setCreateUser(oldEntity.getCreateUser());
        param.setMessage(oldEntity.getMessage());
    }

    @Override
    public CbMessagesResult findBySpec(CbMessagesParam param){
        return null;
    }

    @Override
    public List<CbMessagesResult> findListBySpec(CbMessagesParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(CbMessagesParam param){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    private Serializable getKey(CbMessagesParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private CbMessages getOldEntity(CbMessagesParam param) {
        return this.getById(getKey(param));
    }

    private CbMessages getEntity(CbMessagesParam param) {
        CbMessages entity = new CbMessages();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

    /**
     * 企业获取简历消息
     * @param param
     * @return
     */
    @Override
    public LayuiPageInfo getResumeMessageList(CbMessagesParam param){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.getResumeMessageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    /**
     * 员工获取投递消息
     * @param param
     * @return
     */
    @Override
    public LayuiPageInfo getStaffResumeMessageList(CbMessagesParam param) {
//        return this.baseMapper.getStaffResumeMessageList(param);
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.getStaffResumeMessageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }


    /**
     * 企业查看员工消息
     * @param param
     * @return
     */
    @Override
    public LayuiPageInfo getOtherMessageList(CbMessagesParam param){
//        return this.baseMapper.getOtherMessageList(param);
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.getOtherMessageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public LayuiPageInfo getSysMessageList(CbMessagesParam param) {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.getSysMessageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    /**
     * 员工获取其他消息
     * @param param
     * @return
     */
    @Override
    public LayuiPageInfo getStaffOtherMessageList(CbMessagesParam param) {
//        return this.baseMapper.getStaffOtherMessageList(param);
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.getStaffOtherMessageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    /**
     * 学生获取其他消息
     * @param param
     * @return
     */
    @Override
    public LayuiPageInfo getStudentOtherMessageList(CbMessagesParam param) {
//        return this.baseMapper.getStudentOtherMessageList(param);
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.getStudentOtherMessageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    /**
     * 学生获取被邀请的投递信息
     * @param param
     * @return
     */
    @Override
    public LayuiPageInfo getInvitationMessageList(CbMessagesParam param) {
//        return this.baseMapper.getInvitationMessageList(param);
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.getInvitationMessageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    /**
     * 是否成功交互过联系方式
     * @param param
     * @return
     */
    @Override
    public Integer getContactFlg(CbMessagesParam param) {
        return this.baseMapper.getContactFlg(param);
    }

    @Override
    public List<CbCustomerStudentsResult> getStudentBySchoolNoList(CbMessagesParam param){
        return this.baseMapper.getStudentBySchoolNoList(param);
    }

    /**
     * 消息类型数量
     * @param param
     * @return
     */
    @Override
    public Integer getCountByType(CbMessagesParam param) {
        return this.baseMapper.getCountByType(param);
    }

    /**
     * 发送系统消息
     */
    @Override
    public void sendSysMessage(CbMessagesParam param){
        try{
            Long type = param.getMessageUserid();//接收人类型 1：企业 2：员工 3：学生 0：所有人
            List<Long> userIdList = new ArrayList<>();
            if (1L == type) {
                CbCustomerCompanyParam companyParam = new CbCustomerCompanyParam();
                List<CbCustomerCompanyResult> companyList = companyService.findListBySpec(companyParam);
                for (CbCustomerCompanyResult company: companyList){
                    userIdList.add(company.getId());
                }
            }else if (2L == type){
                CbCustomerStaffParam staffParam = new CbCustomerStaffParam();
                List<CbCustomerStaffResult> staffList = staffService.findListBySpec(staffParam);
                for (CbCustomerStaffResult staff: staffList){
                    userIdList.add(staff.getId());
                }
            }else if (3L == type){
                CbCustomerStudentsParam studentParam = new CbCustomerStudentsParam();
                List<CbCustomerStudentsResult> studentList = studentsService.findListBySpec(studentParam);
                for (CbCustomerStudentsResult student: studentList){
                    userIdList.add(student.getId());
                }
            }else {
                //企业用户
                CbCustomerCompanyParam companyParam = new CbCustomerCompanyParam();
                List<CbCustomerCompanyResult> companyList = companyService.findListBySpec(companyParam);
                for (CbCustomerCompanyResult company: companyList){
                    userIdList.add(company.getId());
                }

                //员工用户
                CbCustomerStaffParam staffParam = new CbCustomerStaffParam();
                List<CbCustomerStaffResult> staffList = staffService.findListBySpec(staffParam);
                for (CbCustomerStaffResult staff: staffList){
                    userIdList.add(staff.getId());
                }

                //普通用户
                CbCustomerStudentsParam studentParam = new CbCustomerStudentsParam();
                List<CbCustomerStudentsResult> studentList = studentsService.findListBySpec(studentParam);
                for (CbCustomerStudentsResult student: studentList){
                    userIdList.add(student.getId());
                }
            }

            Long sendUserid = LoginContextHolder.getContext().getUserId();//消息发送人
            for (Long messageUserid: userIdList) {
                CbMessages entity = getEntity(param);
                entity.setSendUserid(sendUserid);
                entity.setMessageUserid(messageUserid);
                entity.setStatus(0L);
                entity.setType(9L);
                this.save(entity);
            }
        }catch (Exception e){
            logger.error("sendSysMessage error: ", e);
        }
    }

    /**
     * 员工申请操作
     * @param cbMessagesParam
     */
    @Override
    public void handleEmployeeApplication(CbMessagesParam cbMessagesParam){
        try{
            this.update(cbMessagesParam);

            Integer status = 0;//审核状态
//        cbMessagesParam1.setCreateUser(cbMessagesParam.getMessageUserid());
            if (cbMessagesParam.getType() == 7) {
                CbMessagesParam cbMessagesParam1 = new CbMessagesParam();
                cbMessagesParam1.setMessage("企业已经同意你的退出申请");
                cbMessagesParam1.setSendUserid(cbMessagesParam.getMessageUserid());//回复消息
            } else {
                //如果申请统一则新增一个消息
                if (cbMessagesParam.getEventid() == 1) {
                    //查询该学校内所有学生，给所有学生发消息有新学长加入
                    List<CbCustomerStudentsResult> list = this.getStudentBySchoolNoList(cbMessagesParam);
                    for (int i  = 0 ;i<list.size();i++){
                        CbMessagesParam cbMessagesParam1 = new CbMessagesParam();
                        cbMessagesParam1.setSendUserid(cbMessagesParam.getSendUserid());//回复消息
//                  cbMessagesParam1.setType(3L);
                        cbMessagesParam1.setType(8L);
                        cbMessagesParam1.setMessage("你有新学长加入,可以为你介绍更多职位。");
                        cbMessagesParam1.setStatus(0L);
                        cbMessagesParam1.setMessageUserid(list.get(i).getId());
                        this.add(cbMessagesParam1);
                    }
                    status = 2;
                } else {
                    //拒绝后，给员工发拒绝消息
                    CbMessagesParam cbMessagesParam1 = new CbMessagesParam();
                    cbMessagesParam1.setSendUserid(cbMessagesParam.getMessageUserid());//回复消息
                    cbMessagesParam1.setType(7L);
                    cbMessagesParam1.setMessage("该公司拒绝你的申请，拒绝理由：" + cbMessagesParam.getMessage());
                    cbMessagesParam1.setMessageUserid(cbMessagesParam.getSendUserid());
                    cbMessagesParam1.setStatus(0L);
                    this.add(cbMessagesParam1);
                    status = 3;
                }
            }
            //更新员工状态
            CbCustomerStaffParam staffParam = new CbCustomerStaffParam();
            staffParam.setId(cbMessagesParam.getSendUserid());
            staffParam.setStatus(status);
            staffService.update(staffParam);
        }catch (Exception e) {
            logger.error("员工申请操作 handleEmployeeApplication error: ", e);
        }
    }

    /**
     * handleSwapInformation
     * @param cbMessagesParam
     */
    @Override
    public void handleSwapInformation(CbMessagesParam cbMessagesParam){
        try{
            this.update(cbMessagesParam);

            //如果申请统一则新增一个消息
            if (cbMessagesParam.getEventid() == 1) {
                //获取用户的联系方式
                LoginUser user = LoginContextHolder.getContext().getUser();
                String phone = user.getAccount();
                CbMessagesParam cbMessagesParam1 = new CbMessagesParam();
                cbMessagesParam1.setMessageUserid(cbMessagesParam.getSendUserid());
                cbMessagesParam1.setSendUserid(cbMessagesParam.getMessageUserid());
//            cbMessagesParam1.setCreateUser(cbMessagesParam.getMessageUserid());
                cbMessagesParam1.setType(3L);
                cbMessagesParam1.setMessage(phone);
                cbMessagesParam1.setStatus(0L);
                cbMessagesParam1.setEventid(1L);
                this.add(cbMessagesParam1);
            }
        }catch (Exception e) {
            logger.error("handleSwapInformation error: ", e);
        }
    }

    /**
     * 今日消息
     * @param paramCondition
     * @return
     */
    @Override
    public List<CbMessagesResult> getMessageByNow(CbMessagesParam paramCondition) {
        return this.baseMapper.getMessageByNow(paramCondition);
    }
}
